{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<div style=\"color:#777777;background-color:#ffffff;font-size:12px;text-align:right;\">\n",
    "\tprepared by Abuzer Yakaryilmaz (QuSoft@Riga) | November 07, 2018\n",
    "</div>\n",
    "<table><tr><td><i> I have some macros here. If there is a problem with displaying mathematical formulas, please run me to load these macros.</i></td></td></table>\n",
    "$ \\newcommand{\\bra}[1]{\\langle #1|} $\n",
    "$ \\newcommand{\\ket}[1]{|#1\\rangle} $\n",
    "$ \\newcommand{\\braket}[2]{\\langle #1|#2\\rangle} $\n",
    "$ \\newcommand{\\inner}[2]{\\langle #1,#2\\rangle} $\n",
    "$ \\newcommand{\\biginner}[2]{\\left\\langle #1,#2\\right\\rangle} $\n",
    "$ \\newcommand{\\mymatrix}[2]{\\left( \\begin{array}{#1} #2\\end{array} \\right)} $\n",
    "$ \\newcommand{\\myvector}[1]{\\mymatrix{c}{#1}} $\n",
    "$ \\newcommand{\\myrvector}[1]{\\mymatrix{r}{#1}} $\n",
    "$ \\newcommand{\\mypar}[1]{\\left( #1 \\right)} $\n",
    "$ \\newcommand{\\mybigpar}[1]{ \\Big( #1 \\Big)} $\n",
    "$ \\newcommand{\\sqrttwo}{\\frac{1}{\\sqrt{2}}} $\n",
    "$ \\newcommand{\\dsqrttwo}{\\dfrac{1}{\\sqrt{2}}} $\n",
    "$ \\newcommand{\\onehalf}{\\frac{1}{2}} $\n",
    "$ \\newcommand{\\donehalf}{\\dfrac{1}{2}} $\n",
    "$ \\newcommand{\\hadamard}{ \\mymatrix{rr}{ \\sqrttwo & \\sqrttwo \\\\ \\sqrttwo & -\\sqrttwo }} $\n",
    "$ \\newcommand{\\vzero}{\\myvector{1\\\\0}} $\n",
    "$ \\newcommand{\\vone}{\\myvector{0\\\\1}} $\n",
    "$ \\newcommand{\\vhadamardzero}{\\myvector{ \\sqrttwo \\\\  \\sqrttwo } } $\n",
    "$ \\newcommand{\\vhadamardone}{ \\myrvector{ \\sqrttwo \\\\ -\\sqrttwo } } $\n",
    "$ \\newcommand{\\myarray}[2]{ \\begin{array}{#1}#2\\end{array}} $\n",
    "$ \\newcommand{\\X}{ \\mymatrix{cc}{0 & 1 \\\\ 1 & 0}  } $\n",
    "$ \\newcommand{\\Z}{ \\mymatrix{rr}{1 & 0 \\\\ 0 & -1}  } $\n",
    "$ \\newcommand{\\Htwo}{ \\mymatrix{rrrr}{ \\frac{1}{2} & \\frac{1}{2} & \\frac{1}{2} & \\frac{1}{2} \\\\ \\frac{1}{2} & -\\frac{1}{2} & \\frac{1}{2} & -\\frac{1}{2} \\\\ \\frac{1}{2} & \\frac{1}{2} & -\\frac{1}{2} & -\\frac{1}{2} \\\\ \\frac{1}{2} & -\\frac{1}{2} & -\\frac{1}{2} & \\frac{1}{2} } } $\n",
    "$ \\newcommand{\\CNOT}{ \\mymatrix{cccc}{1 & 0 & 0 & 0 \\\\ 0 & 1 & 0 & 0 \\\\ 0 & 0 & 0 & 1 \\\\ 0 & 0 & 1 & 0} } $\n",
    "$ \\newcommand{\\norm}[1]{ \\left\\lVert #1 \\right\\rVert } $"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<h2> One Bit </h2>\n",
    "\n",
    "In daily life, we use decimal number system. It is also called base-10 system, because we have 10 digits:\n",
    "\n",
    "$ 0,~1,~2,~3,~4,~5,~6,~7,~8, \\mbox{ and } 9  $.\n",
    "\n",
    "In computer science, on the other hand, the widely used system is binary, which has only two digits:\n",
    "\n",
    "$ 0 $ and $ 1 $.\n",
    "\n",
    "One bit (or binary digit) is the basic unit of information used in computer science. \n",
    "\n",
    "It can also be seen as the smallest \"useful\" memory unit, which has two states named 0 and 1. \n",
    "\n",
    "One bit can be in (or store) either 0 or 1."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<h3> Four operators </h3>\n",
    "\n",
    "How many different operators can be defined on a single bit?\n",
    "\n",
    "<i>An operator, depending on the current state of the bit, updates the state of bit (the result may be the same state).</i> \n",
    "\n",
    "We can apply four different operators to a single bit:\n",
    "<ol>\n",
    "    <li> Identity: $ I(0) = 0 $ and $ I(1) = 1 $ </li>\n",
    "    <li> Negation: $ NOT(0) = 1 $ and $ NOT(1) = 0 $ </li>\n",
    "    <li> Constant (Zero): $ ZERO(0) = 0 $ and $ ZERO(1) = 0 $ </li>\n",
    "    <li> Constant (One): $ ONE(0) = 1 $ and $ ONE(1) = 1 $ </li>\n",
    "</ol>\n",
    "The first operator is called IDENTITY, because it does not change the content/value of the bit.\n",
    "\n",
    "The second operator is named NOT, bacause it negates (flips) the value of bit. \n",
    "\n",
    "<i>Remark that 0 and 1 also refers to Boolean values False and True, respectively, and, False is the negation of True, and True is the negation of False.</i>\n",
    "\n",
    "The third (resp., fourth) operator returns a constant value 0 (resp., 1), whatever the input is."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<h3> Table representation </h3>\n",
    "\n",
    "Let's represent the transition of each operator by a table. \n",
    "\n",
    "In each table,\n",
    "<ul>\n",
    "    <li> the header (first row) representing the initial values, </li>\n",
    "    <li> the first column representing the final values, </li>\n",
    "    <li> we use 1 if there is a transition between two values, and, </li>\n",
    "    <li> we use 0 if there is no transition between two values. </li>\n",
    "</ul>\n",
    "\n",
    "The table representation of the identity operator is given below:\n",
    "\n",
    "$\n",
    "I = \\begin{array}{c|cc} & \\mathbf{0} & \\mathbf{1} \\\\ \\hline \\mathbf{0} & 1 & 0 \\\\  \\mathbf{1} & 0 & 1  \\end{array}\n",
    "$\n",
    "\n",
    "The values in <b>bold</b> are the initial and final values of the bits. The non-bold values represent the transitions.\n",
    "<ul>\n",
    "    <li> The top-left non-bold 1 represents the transtion $ 0 \\rightarrow 0 $. </li>\n",
    "    <li> The bottom-right non-bold 1 represents the transtion $ 1 \\rightarrow 1 $. </li> \n",
    "    <li> The top-right non-bold 0 means that there is no transition from 1 to 0. </li>\n",
    "    <li> The bottom-left non-bold 0 means that there is no transition from 0 to 1. </li>\n",
    "</ul>\n",
    "The reader may think the values 0 and 1 representing the transitions as True (On) and False (Off), respectively. \n",
    "\n",
    "Similarly, we can represent the other operators as below:\n",
    "\n",
    "$\n",
    "NOT = \\begin{array}{c|cc} & \\mathbf{0} & \\mathbf{1} \\\\ \\hline \\mathbf{0} & 0 & 1 \\\\ \\mathbf{1} & 1 & 0  \\end{array}\n",
    "~~~~~~~~\n",
    "ZERO = \\begin{array}{c|cc} & \\mathbf{0} & \\mathbf{1} \\\\ \\hline \\mathbf{0} & 1 & 1 \\\\  \\mathbf{1} & 0 & 0  \\end{array}\n",
    "~~~~~~~~\n",
    "ONE = \\begin{array}{c|cc} & \\mathbf{0} & \\mathbf{1} \\\\ \\hline \\mathbf{0} & 0 & 0 \\\\  \\mathbf{1} & 1 & 1  \\end{array}\n",
    ".\n",
    "$"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<h3> Task 1 </h3>\n",
    "\n",
    "Convience yourself with the correctness of each table."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<h3> Reversibility and Irreversibility </h3>\n",
    "\n",
    "After applying Identity or NOT operatotor, we can easily determine the initial value by checking the final value. \n",
    "<ul>\n",
    "    <li> In the case of Identity operator, we simply say the same value. </li>\n",
    "    <li> In the case of NOT operator, we simply say the other value, i.e., if the final value is 0 (resp., 1), then we say 1 (resp., 0). </li>\n",
    "</ul>\n",
    "\n",
    "However, we cannot know the initial value by checking the final value after applying ZERO or ONE operator. \n",
    "\n",
    "Based on this observation, we can classify the operators into two types: <i>Reversible</i> and <i>Irreversible</i>.\n",
    "<ul>\n",
    "    <li> If we can recover the initial value(s) from the final value(s), then the operator is called reversible like Identity and NOT operators. </li>\n",
    "    <li> If we cannot know the initial value(s) from the final value(s), then the operator is called irreversible like ZERO and ONE operators. </li>\n",
    "</ul>\n",
    "\n",
    "<b> This classification is important, because, as will be seen later, the quantum evolution operators are reversible. </b>\n",
    "\n",
    "The identity operator does not have any affect on the computation, and so it is not interesting.\n",
    "\n",
    "But we will widely use NOT operator in our quantum algortihms.         "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<h3> Our first quantum circuit </h3>\n",
    "\n",
    "For our quantum programs, we will design quantum circuits.\n",
    "\n",
    "As a warm-up example, here we design a circuit with a single quantum bit.\n",
    "\n",
    "We also highlight the details on designing quantum circuits along with our codes."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# \n",
    "# A quantum circuit is composed by quantum and classical bits.\n",
    "#\n",
    "\n",
    "# here are the objects that we use to create a quantum circuit\n",
    "from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit\n",
    "\n",
    "# we use a quantum register to keep our quantum bits.\n",
    "qreg =  QuantumRegister(1) # in this example we will use a single quantum bit\n",
    "\n",
    "# To get an information from a quantum bit, it must be measured. (More details will appear.)\n",
    "#     The measurement result is stored classically.\n",
    "#     Therefore, we also use a classical regiser with classical bits\n",
    "creg = ClassicalRegister(1) # in this example we will use a single classical bit\n",
    "\n",
    "# now we can define our quantum circuit\n",
    "# it is composed by a quantum and a classical register\n",
    "mycircuit = QuantumCircuit(qreg,creg)\n",
    "\n",
    "# we apply operators on quantum bits\n",
    "# operators are also called as gates\n",
    "# we apply NOT operator represented as \"x\"\n",
    "# operator is a part of the circuit, and we should specify the quantum bit as the parameter\n",
    "mycircuit.x(qreg[0]) # (quantum) bits are enumerated starting from 0\n",
    "# NOT operator or x-gate is applied to the first qubit of the quantum register\n",
    "\n",
    "# let's run our codes until now, and then draw our circuit\n",
    "print(\"Everything looks fine, let's continue ...\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# we use matplotlib_circuit_drawer\n",
    "#     we shortly refer it as \"drawer\" in our codes\n",
    "from qiskit.tools.visualization import matplotlib_circuit_drawer as drawer\n",
    "\n",
    "# let's draw our circuit now \n",
    "drawer(mycircuit)\n",
    "# re-execute me if you DO NOT see the circuit diagram"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<b>Congratulations!</b> if you see your diagram :-)\n",
    "\n",
    "<i><u> Remak</u></i>: Qiskit has its own counters to enumerate the objects ($ q2_0 $, $ c2_0 $, etc.). \n",
    "<ul>\n",
    "    <li> They might be useful for debugging, but currently you can simply discard this part.\n",
    "    <li> You may also notice that when you re-run the same codes, the index of objects will be increased.\n",
    "</ul>\n",
    "\n",
    "The value of the quantum bit is 0 at the beginning. Technically, we denote is as $ \\ket{0} $, called <b><i>ket</i>-notation</b>.\n",
    "\n",
    "The value of the classical bit is also 0 at the beginning. \n",
    "\n",
    "Classical or quantum, each bit is represented as a straight line. You may think of it as a wire.\n",
    "\n",
    "The x-gate is shown as a square.\n",
    "\n",
    "The value of the quantum bit is expected to be $ \\ket{1} $ after the operator.\n",
    "\n",
    "Let's measure the first qubit (define a mesurement operator), and then execute our circuit and see the result."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# measurement is defined by associating a quantum bit to a classical bit\n",
    "mycircuit.measure(qreg[0],creg[0])\n",
    "# the result will be stored in the classical bit\n",
    "\n",
    "print(\"Everything looks fine, let's continue ...\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# let's draw the circuit again to see how the measurement is defined\n",
    "drawer(mycircuit)\n",
    "# reexecute me if you DO NOT see the circuit diagram"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# we are done with design of our circuit\n",
    "# now we can execute it\n",
    "# we execute quantum circuits many times (WHY?)\n",
    "\n",
    "# we use method \"execute\" and object \"Aer\" from qiskit library\n",
    "from qiskit import execute, Aer\n",
    "\n",
    "# we create a job object for execution of the circuit\n",
    "# there are three parameters\n",
    "#     1. mycircuit\n",
    "#     2. beckend on which it will be executed: we will use local simulator\n",
    "#     3. how_many_times will it be executed, let's pick it as 1024\n",
    "job = execute(mycircuit,Aer.get_backend('qasm_simulator'),shots=1024)\n",
    "\n",
    "# we can get the result of the outcome as follows\n",
    "counts = job.result().get_counts(mycircuit)\n",
    "print(counts)\n",
    "\n",
    "# usually quantum programs produce probabilistic outcomes "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We expect to see 1 in each execution, and so the output should be $ \\{\\mbox{'1'}:~1024\\} $. \n",
    "\n",
    "That is, the outcome 1 is measured 1024 times.\n",
    "\n",
    "<i>The output is composed by pairs, and each pair showing the measurement outcome and how many times it was measured.</i> \n",
    "<br>\n",
    "<i>For example, if the output is $ \\{\\mbox{'0': 500, '1': 524}\\} $, then we know that the outcome 0 is measured 500 times and the outcome 1 is measured 524 times. </i>\n",
    "\n",
    "<b><i> Quantum programs usually give probabilistic outcomes. \n",
    "    \n",
    "Therefore, we should execute them many times to get more reliable outcomes. </b></i> "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<h3> My second quantum circuit </h3>\n",
    "\n",
    "Let's create a quantum circuit with four quantum bits. \n",
    "\n",
    "We use almost the same code with small modifications. \n",
    "\n",
    "Our comments explain only the modifications."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# \n",
    "# My second quantum circuit\n",
    "#\n",
    "\n",
    "# we import all at once\n",
    "from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer\n",
    "from qiskit.tools.visualization import matplotlib_circuit_drawer as drawer\n",
    "\n",
    "# we will use 4 quantum bits and 4 classical bits\n",
    "qreg2 =  QuantumRegister(4)\n",
    "creg2 = ClassicalRegister(4)\n",
    "\n",
    "mycircuit2 = QuantumCircuit(qreg2,creg2)\n",
    "\n",
    "# I will apply x-gate to the first quantum bit twice\n",
    "mycircuit2.x(qreg2[0])\n",
    "mycircuit2.x(qreg2[0])\n",
    "\n",
    "# I will apply x-gate to the fourth quantum bit once\n",
    "mycircuit2.x(qreg2[3])\n",
    "\n",
    "# I will apply x-gate to the third quantum bit three times\n",
    "mycircuit2.x(qreg2[2])\n",
    "mycircuit2.x(qreg2[2])\n",
    "mycircuit2.x(qreg2[2])\n",
    "\n",
    "# I will apply x-gate to the second quantum bit four times\n",
    "mycircuit2.x(qreg2[1])\n",
    "mycircuit2.x(qreg2[1])\n",
    "mycircuit2.x(qreg2[1])\n",
    "mycircuit2.x(qreg2[1])\n",
    "\n",
    "# if the size of quantum and classical registers are the same, we can define measurements with a single line code\n",
    "mycircuit2.measure(qreg2,creg2)\n",
    "# then each quantum bit and classical bit is associated with respect to their indices\n",
    "\n",
    "# let's run our codes until now, and then draw our circuit\n",
    "\n",
    "print(\"Everything looks fine, let's continue ...\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "drawer(mycircuit2)\n",
    "# re-execute me if you DO NOT see the circuit diagram"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<h3> Task 2 </h3>\n",
    "\n",
    "Guess the outcome by checking the circuit.\n",
    "\n",
    "Then, compare your guess with the result obtained after executing our circuit 500 times."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "job = execute(mycircuit2,Aer.get_backend('qasm_simulator'),shots=500)\n",
    "counts = job.result().get_counts(mycircuit2)\n",
    "print(counts)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<h3> An important technical note:</h3> \n",
    "\n",
    "In Qiskit the outcomes are read from the classical register bottom to top \n",
    "$$ creg[3],~creg[2],~creg[1],~creg[0] $$\n",
    "and so, we see the <b><u><i>reverse</i></u></b> of what we expected. \n",
    "\n",
    "<i>If you think the overall output as a single number, then it is assumed that the upper bits are the least significant bits.</i>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<h3> Reverse the output </h3>\n",
    "\n",
    "Let's write a method to print the reverse the outcomes as we expected.\n",
    "\n",
    "You may use this method later."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def print_outcomes(counts): # takes a dictionary variable\n",
    "    for outcome in counts: # for each key-value in dictionary\n",
    "        reverse_outcome = ''\n",
    "        for i in outcome: # each string can be considered as a list of characters\n",
    "            reverse_outcome = i + reverse_outcome # each new symbol comes before the old symbol(s)\n",
    "        print(reverse_outcome,\"is observed\",counts[outcome],\"times\")\n",
    "\n",
    "job = execute(mycircuit2,Aer.get_backend('qasm_simulator'),shots=1024)\n",
    "counts = job.result().get_counts(mycircuit2) # counts is a dictionary object in python\n",
    "print_outcomes(counts)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<h3>Pick a random number</h3>\n",
    "\n",
    "In your first circuit design task, you will be asked to apply x-gate randomly.\n",
    "\n",
    "Here is one of the method to pick a random number in python."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from random import randrange\n",
    "n = 20\n",
    "r=randrange(n) # pick a number from the list {0,1,...,n-1}\n",
    "print(r)\n",
    "\n",
    "# test this method by using a loop\n",
    "for i in range(10):\n",
    "    print(randrange(n))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<h3> Task 3 </h3>\n",
    "\n",
    "Design a quantum circuit with 10 quantum bits and 10 classical bits.\n",
    "\n",
    "For each quantum bit, flip a coin, and apply x-gate if the outcome is head.\n",
    "\n",
    "Measure your quantum bits.\n",
    "\n",
    "Execute your circuit 128 times.\n",
    "\n",
    "Repeat this task as mush as you want, and enjoy your random choices."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#\n",
    "# your solution is here\n",
    "#\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<a href=\"..\\bronze-solutions\\B24_One_Bit_Solution.ipynb#task3\">click for our solution</a>"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
